import {useAtom} from "jotai";
import {
    currentPageAtom,
    pageSizeAtom,
    selectedIdsAtom,
    selectedRangeAtom,
    selectedTypeAtom, sortByCountDescAtom,
    sortByDifficultyDescAtom
} from "../../store/atoms";
import {useEffect, useState} from 'react';

import {Question} from "../../types";
import BaseQuesItem from "../BaseQuesItem";

interface Props {
    className?: string;
}

/**
 * 首页考题列表，带勾选框
 * @param className 扩展
 */
function HomePageQuesList({className = ''}: Props) {
    // useAtom返回状态值和状态设置函数，用法同useState
    // 全局状态：已勾选的题目id集合
    const [selectedIds, setSelectedIds] = useAtom(selectedIdsAtom);
    // 已勾选状态
    const [selectedType, setSelectedType] = useAtom(selectedTypeAtom);
    const [selectedRange, setSelectedRange] = useAtom(selectedRangeAtom);
    const [sortByDifficultyDesc, setSortByDifficultyDesc] = useAtom(sortByDifficultyDescAtom);
    const [sortByCountDesc, setSortByCountDesc] = useAtom(sortByCountDescAtom);
    const toggleSelectedIds = (id: number) => {
        if (selectedIds.includes(id)) {
            const newList = selectedIds.filter(i => i !== id);
            setSelectedIds(newList);
            console.log('Removed:', id, 'Result:', newList);
        } else {
            const newList = [...selectedIds, id];
            setSelectedIds(newList);
            console.log('Added:', id, 'Result:', newList);
        }
    };
    // 全局状态：当前页码和每页考题数目
    const [currentPage] = useAtom(currentPageAtom)
    const [pageSize] = useAtom(pageSizeAtom)
    // 内部状态：当前包含的考题列表
    const [quesList, setQuesList] = useState<Question[]>([]);
    // 当后面列表里对象有变化的时候执行，加载时默认执行一遍
    useEffect(() => {
        console.log('update');
        let offset = (currentPage - 1) * pageSize;
        window.ipcRender.invoke('db:getQuesList', {
            limit: pageSize,
            offset: offset,
            type: selectedType,
            rating: selectedRange,
            sortByDiff: sortByDifficultyDesc,
            sortByCount: sortByCountDesc
        }).then((res) => {
            setQuesList(res);
            console.log("当前页题目考题id列表:", res.map((q: Question) => q.id));
        })
    }, [currentPage, pageSize, selectedType, selectedRange, sortByDifficultyDesc, sortByCountDesc]);

    return (
        <div className={`m-2 ${className}`}>
            {quesList.map((question) => (
                <div key={question.id} className="flex items-start gap-2">
                    {/* 左侧勾选框 */}
                    <input type="checkbox"
                           checked={selectedIds.includes(question.id)}
                           onChange={() => toggleSelectedIds(question.id)}
                           className="checkbox checkbox-xl checkbox-accent mt-5"
                    />
                    {/* 右侧题目 */}
                    <div className="flex-1">
                        <BaseQuesItem question={question}/>
                    </div>
                </div>
            ))}
        </div>
    )
}

export default HomePageQuesList;